package com.suke.czx.modules.task.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.suke.czx.common.utils.*;
import com.suke.czx.modules.performance.entity.Performance;
import com.suke.czx.modules.performance.service.PerformanceService;
import com.suke.czx.modules.task.entity.Task;
import com.suke.czx.modules.task.entity.TaskSearchBo;
import com.suke.czx.modules.task.mapper.TaskMapper;
import com.suke.czx.modules.task.service.TaskService;
import com.suke.czx.modules.team.service.TeamService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 应用模块名称: 任务
 * 代码描述: 任务业务层
 * copyright: AUZAR ALL RIGHTS RESERVED
 * company: AUZAR
 *
 * @author: 颜米晨
 * @date: 2021/09/11 17:31
 */
@Service
@AllArgsConstructor
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements TaskService {

    private final TeamService teamService;

    private final PerformanceService performanceService;

    private TaskMapper taskMapper;

    /**
     * 分页查询任务列表
     * @param taskSearchBo 查询BO
     * @return VO
     */
    @Override
    public R pageTaskList(TaskSearchBo taskSearchBo) {
        // 获取一级任务总记录数
        Integer count = taskMapper.countParentTask(taskSearchBo);
        if (count == null || count == 0) {
            return R.ok();
        }
        // 获取任务查询结果集
        List<Task> taskList = taskMapper.pageTaskList(taskSearchBo, (taskSearchBo.getPage() - 1) * taskSearchBo.getLimit(), taskSearchBo.getLimit());
        // 将三级任务按照对应的二级任务id归集数据
        Map<Long, List<Task>> children3Map = taskList.stream().filter(t -> t.getTaskLevel() != null && t.getTaskLevel() == 3 && !StrUtil.isBlankIfStr(t.getParentId()))
                .collect(Collectors.groupingBy(Task::getParentId, HashMap::new, Collectors.toList()));
        // 将二级任务按照对应的一级任务id归集数据
        Map<Long, List<Task>> children2Map = taskList.stream().filter(t -> t.getTaskLevel() != null && t.getTaskLevel() == 2 && !StrUtil.isBlankIfStr(t.getParentId()))
                .peek(t -> t.setChildren(children3Map.get(t.getTaskId()))).collect(Collectors.groupingBy(Task::getParentId, HashMap::new, Collectors.toList()));
        // 分组处理数据集
        List<Task> dataList = taskList.stream().filter(t -> t.getTaskLevel() != null && t.getTaskLevel() == 1)
                .peek(t -> t.setChildren(children2Map.get(t.getTaskId()))).collect(Collectors.toList());
        // 返回结果
        return Objects.requireNonNull(R.ok().put(FieldConstant.TOTAL, count)).setData(dataList);
    }

    /**
     * 保存任务
     * @param task 任务
     * @param userId 操作人员编码
     * @return VO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveTask(Task task, Long userId) {
        if (ListUtil.isEmpty(teamService.searchTeamByProjectId(task.getProjectId()))) {
            return R.error("新建任务前请先新建项目团队");
        }
        if (task.getTaskLevel() != null) {
            switch (task.getTaskLevel()) {
                case CodeConstant.TASK_LEVEL_FIRST:
                    if (task.getProportion() ==  null) {
                        return R.error("一级任务权重不能为空");
                    }
                    break;
                case CodeConstant.TASK_LEVEL_SECOND:
                    if (task.getParentId() == null) {
                        return R.error("二级任务父任务编码不能为空");
                    }
                    if (task.getProgress() == null) {
                        return R.error("二级任务进度不能为空");
                    }
                    if (task.getPerformanceCategory() == null) {
                        return R.error("二级任务绩效分数不能为空");
                    }
                    break;
                case CodeConstant.TASK_LEVEL_THIRD:
                    if (task.getParentId() == null) {
                        return R.error("三级任务父任务编码不能为空");
                    }
                    if (task.getStatus() == null) {
                        return R.error("三级任务状态不能为空");
                    }
                    break;
                default:
                    break;
            }
        }
        // 二级任务同时生成对应的绩效记录
        if (task.getTaskLevel() != null && task.getTaskLevel() == CodeConstant.TASK_LEVEL_SECOND) {
            if (StrUtil.isBlank(task.getUserIds())) {
                return R.error("二级任务生成绩效时员工编码不能为空");
            }
            Performance performance = new Performance();
            performance.setPerformanceName(task.getTaskName() + "绩效");
            performance.setType(CodeConstant.PERFORMANCE_PROJECT_TYPE);
            performance.setUserId(Long.valueOf(Arrays.asList(StrUtil.split(task.getUserIds(), Constant.COMMA)).get(0)));
            performance.setTaskId(task.getTaskId());
            performance.setPerformanceCategory(task.getPerformanceCategory() != null ? task.getPerformanceCategory().doubleValue() : null);
            performance.setCreator(userId);
            performance.setCreateTime(new Date());
            performanceService.save(performance);
        }
        task.setCreator(userId);
        task.setCreateTime(new Date());
        save(task);
        return R.ok();
    }

    /**
     * 删除任务
     * @param taskId 任务编码
     * @param userId 操作者编码
     * @return VO
     */
    @Override
    public R updateDelTask(Long taskId, Long userId) {
        // 校验该任务是否存在子任务
        Integer count = taskMapper.getIfHasChildrenTask(taskId);
        if (count != null && count > 0) {
            return R.error("该任务存在子任务,否则请先删除其关联子任务");
        }
        // 逻辑删除任务
        taskMapper.updateDelTask(taskId, userId);
        return R.ok();
    }

    /**
     * 二级任务状态
     * @param taskId 任务编码
     * @param taskLevel 任务级别
     * @param progress 二级任务状态
     * @param userId 操作者编码
     * @return VO
     */
    @Override
    public R updateTaskProgress(Long taskId, Integer taskLevel, Integer progress, Long userId) {
        taskMapper.updateTaskProgress(taskId, taskLevel, progress, userId);
        return R.ok();
    }

    /**
     * 三级任务状态
     * @param taskId 任务编码
     * @param taskLevel 任务级别
     * @param status 三级任务状态
     * @param userId 操作者编码
     * @return VO
     */
    @Override
    public R updateTaskStatus(Long taskId, Integer taskLevel, Integer status, Long userId) {
        taskMapper.updateTaskStatus(taskId, taskLevel, status, userId);
        return R.ok();
    }

}